<template>
      <van-row>
        <van-col :span="24">
            <van-address-list
                v-model="store.state.chosenAddressId"
                :list="list"
                default-tag-text="默认"
                @add="onAdd"
                @edit="onEdit"
            >
            </van-address-list>
        </van-col>
   </van-row>
</template>
<script setup>
    import { showToast,showNotify } from 'vant';
    import { ref,onMounted,getCurrentInstance } from "vue";
    import store from '@/store';

    const {proxy} = getCurrentInstance(); 
    
    const list=ref([]);
    const userId=ref(null);
    const addressList=ref([]);
    const getAddressByUserId=()=>{
        proxy.$axios({
            method:'get',
            url:'/address/user/'+userId.value
        }).then(res=>{
            let resultBean=res.data;
            if(resultBean.code==200) {
                addressList.value=resultBean.data;
                addressList.value.forEach(address=>{
                    list.value.push({
                        id:address.addressId,
                        name: address.contactName,
                        tel: address.contactTel,
                        address: address.address,
                    })
                })
                if(list.value.length>0) {
                    list.value[0].isDefault=true;
                    if(!store.state.chosenAddressId) {
                        store.state.choseAddressId=list.value[0].id;
                    }
                }
            } else {
                showNotify({message:resultBean.msg});
            }
        }).catch(error=>{
            showNotify({message:error.message})
        })
    }
    const onAdd=()=>{
        proxy.$router.push('/main/addAddress');
    }
    const onEdit=(item,index)=>showToast('编辑地址'+index);
    onMounted(()=>{
        let userJson = window.localStorage.getItem("loginUser");
            if(userJson==null) {
                showNotify({message:'请先登录'})
                proxy.$router.push('/login');
                return;
            }
            //进行赋值
        let user = JSON.parse(userJson);

        //这还有一点歧义
        userId.value=user.userId;
        getAddressByUserId();
    })
</script>